package com.shoy.myapp.common.task;

import android.util.Log;
import com.shoy.myapp.BuildConfig;
import com.shoy.myapp.app.AppManager;
import com.shoy.myapp.common.Utils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;

/**
 * Http连接管理
 * Created by shoy on 2014/9/4.
 */
public final class HttpConnectionManager {
    private final static String TAG = "HttpConnectionManager";
    private static HttpParams httpParams;
    private static ClientConnectionManager connectionManager;

    /**
     * 最大连接数
     */
    public final static int MAX_TOTAL_CONNECTIONS = 800;
    /**
     * 获取连接的最大等待时间
     */
    public final static int WAIT_TIMEOUT = 60000;
    /**
     * 每个路由最大连接数
     */
    public final static int MAX_ROUTE_CONNECTIONS = 400;
    /**
     * 连接超时时间
     */
    public final static int CONNECT_TIMEOUT = 60000;
    /**
     * 读取超时时间
     */
    public final static int READ_TIMEOUT = 60000;

    static {
        httpParams = new BasicHttpParams();
        // 设置最大连接数
        ConnManagerParams.setMaxTotalConnections(httpParams, MAX_TOTAL_CONNECTIONS);
        // 设置获取连接的最大等待时间
        ConnManagerParams.setTimeout(httpParams, WAIT_TIMEOUT);
        // 设置每个路由最大连接数
        ConnPerRouteBean connPerRoute = new ConnPerRouteBean(MAX_ROUTE_CONNECTIONS);
        ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRoute);
        // 设置连接超时时间
        HttpConnectionParams.setConnectionTimeout(httpParams, CONNECT_TIMEOUT);
        // 设置读取超时时间
        HttpConnectionParams.setSoTimeout(httpParams, READ_TIMEOUT);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        try {
            registry.register(new Scheme("https", new TrustAllSSLSocketFactory(), 443));
        } catch (KeyManagementException e) {
            Log.e(TAG, e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, e.getMessage(), e);
        } catch (KeyStoreException e) {
            Log.e(TAG, e.getMessage(), e);
        } catch (UnrecoverableKeyException e) {
            Log.e(TAG, e.getMessage(), e);
        }

        connectionManager = new ThreadSafeClientConnManager(httpParams, registry);
    }

    private static HttpClient httpClient;

    /**
     * 获取HttpClient实例
     *
     * @return HttpClient
     */
    public static HttpClient getHttpClient() {
        if (httpClient == null)
            httpClient = new DefaultHttpClient(connectionManager, httpParams);
        return httpClient;
    }

    /**
     * 获取Http请求返回数据
     *
     * @param client  HttpClient
     * @param request Request
     * @return 返回数据
     * @throws java.io.IOException
     */
    public static String parseBodyAsString(HttpClient client, HttpUriRequest request) throws IOException {
        request.setHeader("Connection", "Keep-Alive");
        request.setHeader("User-Agent", Utils.getUserAgent(AppManager.getInstance().current()));
        InputStream is = client.execute(request).getEntity().getContent();
        InputStreamReader isr = new InputStreamReader(is, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        while (line != null) {
            sb.append(line);
            line = br.readLine();
        }
        isr.close();
        if (BuildConfig.DEBUG)
            Log.d(TAG, sb.toString());
        return sb.toString();
    }

    public static String parseBodyAsString(InputStream is) throws IOException {
        InputStreamReader isr = new InputStreamReader(is, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        while (line != null) {
            sb.append(line);
            line = br.readLine();
        }
        isr.close();
        if (BuildConfig.DEBUG)
            Log.d(TAG, sb.toString());
        return sb.toString();
    }
}
